import { login, logout, getUserInfo } from '@/api/user'
import { setToken, getToken } from '@/libs/util'

export default {
  state: {
    userName: '',
    userCode: '',
    identity: '',
    department: '',
    enabled: false,
    avatorImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false
  },
  getters: {
    userInfo: state => state
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    // setUserId (state, id) {
    //   state.userId = id
    // },
    setUserCode (state, code) {
      state.userCode = code
    },
    setUserName (state, name) {
      state.userName = name
    },
    setAccess (state, access) {
      state.access = access
    },
    setIdentity (state, identity) {
      state.identity = identity
    },
    setEnabled (state, enabled) {
      state.enabled = enabled
    },
    setDepartment (state, department) {
      state.department = department
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    }
  },
  actions: {
    // 登录
    handleLogin ({ commit }, {userName, password}) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password
        }).then(res => {
          const data = res.data
          commit('setToken', data.token)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo().then(response => {
            const res = response.data
            if (res.code === 1) {
              commit('setAvator', res.data.avator)
              commit('setUserName', res.data.name)
              commit('setUserCode', res.data.code)
              commit('setAccess', res.data.roles)
              commit('setIdentity', res.data.identity)
              commit('setEnabled', res.data.enabled)
              commit('setDepartment', res.data.department)
              commit('setHasGetInfo', true)
              resolve(response)
            }
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
